package com.example.springboot_demo.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    /**
     * 单文件上传并返回文件流
     */
    @PostMapping("/upload")
    public ResponseEntity<byte[]> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 获取文件字节流
        byte[] fileBytes = file.getBytes();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getOriginalFilename());

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }

    /**
     * 多文件上传并返回第一个文件流
     */
    @PostMapping("/uploadMultiple")
    public ResponseEntity<byte[]> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) throws IOException {
        if (files.length == 0) {
            throw new RuntimeException("至少需要上传一个文件");
        }

        MultipartFile firstFile = files[0];
        byte[] fileBytes = firstFile.getBytes();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", firstFile.getOriginalFilename());

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }

    /**
     * 使用 HttpServletResponse 直接输出文件流
     */
    @PostMapping("/uploadAndStream")
    public void uploadAndStream(@RequestParam("file") MultipartFile file,
                                HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getOriginalFilename());

        // 获取输入流并写入响应输出流
        try (InputStream inputStream = file.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        }
    }
}